package com.begye.smartloan.apptest.certify

import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Bitmap
import android.os.Bundle
import android.util.Log
import androidx.activity.enableEdgeToEdge
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.PickVisualMediaRequest
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.begye.smartloan.apptest.R
import com.begye.smartloan.apptest.certify.adapter.CertifySalaryImageAdapter
import com.begye.smartloan.apptest.certify.adapter.CertifySelfieImageAdapter
import com.begye.smartloan.apptest.databinding.AtCertifyBinding
import com.begye.smartloan.apptest.gongong.YongHuJiDingYiViewModel
import com.begye.smartloan.apptest.gongong.YongHuLiuChengViewModel
import com.begye.smartloan.apptest.homebefore.HomeBeforeActivity
import com.begye.smartloan.apptest.kefu.KeFuDialogFragment
import com.begye.smartloan.apptest.renzheng.RenZhengActivity
import com.begye.smartloan.apptest.renzheng.alldone.RenZhengAllDoneActivity
import com.begye.smartloan.apptest.renzheng.bangka.RenZhengBangKaActivity
import com.begye.smartloan.apptest.renzheng.dialog.DocumentSourceTypeDialogFragment
import com.begye.smartloan.apptest.renzheng.dialog.FillItemSelectListDialogFragment
import com.begye.smartloan.apptest.renzheng.document.RenZhengDocumentActivity
import com.begye.smartloan.apptest.renzheng.document.RenZhengDocumentCaptureActivity
import com.begye.smartloan.apptest.renzheng.lianxiren.RenZhengLianXiRenActivity
import com.begye.smartloan.apptest.renzheng.selfie.RenZhengSelfieActivity
import com.begye.smartloan.apptest.tool.SysConfigTool
import com.begye.smartloan.apptest.tool.addTouch
import com.util.utillib.extend.IntentFlagMode
import com.util.utillib.extend.toNextActivity
import com.vmadalin.easypermissions.EasyPermissions
import com.vmadalin.easypermissions.dialogs.DEFAULT_SETTINGS_REQ_CODE
import com.vmadalin.easypermissions.dialogs.SettingsDialog
import kotlin.math.min


@SuppressLint("CustomWelcomeScreen")
class CertifyActivity : AppCompatActivity(), EasyPermissions.PermissionCallbacks,
    EasyPermissions.RationaleCallbacks {

    private lateinit var _binding: AtCertifyBinding
    private lateinit var _fillSelectListDialogFragment: FillItemSelectListDialogFragment

    private lateinit var _certifySalaryImageAdapter: CertifySalaryImageAdapter
    private lateinit var _certifySelfieImageAdapter: CertifySelfieImageAdapter

    private lateinit var _pickMedia: ActivityResultLauncher<PickVisualMediaRequest>

    private val _yongHuLiuChengViewModel by lazy {
        ViewModelProvider(this)[YongHuLiuChengViewModel::class.java]
    }

    private val _certifyViewModel by lazy {
        ViewModelProvider(this)[CertifyViewModel::class.java]
    }

    private val _yongHuJiDingYiViewModel by lazy {
        ViewModelProvider(this)[YongHuJiDingYiViewModel::class.java]
    }

    @SuppressLint("NotifyDataSetChanged")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()

        _binding = AtCertifyBinding.inflate(layoutInflater)
        setContentView(_binding.root)

        configYongHuLiuChengState()
        configUIState()
        configUIEvent()
        configUIData()
    }

    private fun configYongHuLiuChengState() {

        _certifyViewModel.onLoadingStateLiveData.observe(this) {
            if (it == true) {
                _binding.atGlobalLoading.show()
            } else {
                _binding.atGlobalLoading.hide()
            }
        }

        _yongHuLiuChengViewModel.onLoadingStateLiveData.observe(this) {
            if (it == true) {
                _binding.atGlobalLoading.show()
            } else {
                _binding.atGlobalLoading.hide()
            }
        }

        _yongHuJiDingYiViewModel.onLoadingStateLiveData.observe(this) {
            if (it == true) {
                _binding.atGlobalLoading.show()
            } else {
                _binding.atGlobalLoading.hide()
            }
        }

        _yongHuLiuChengViewModel.onDoingRenZhengPageLiveData.observe(this) {
            if (it) {
                toNextActivity(
                    activity = RenZhengActivity::class.java,
                    mode = IntentFlagMode.SINGLE_TOP
                )
            }
        }

        _yongHuLiuChengViewModel.onDoingLianXiRenPageLiveData.observe(this) {
            if (it) {
                toNextActivity(
                    activity = RenZhengLianXiRenActivity::class.java,
                    mode = IntentFlagMode.SINGLE_TOP
                )
            }
        }

        _yongHuLiuChengViewModel.onDoingBangKaFrPageLiveData.observe(this) {
            if (it) {
                toNextActivity(
                    activity = RenZhengBangKaActivity::class.java,
                    mode = IntentFlagMode.SINGLE_TOP
                )
            }
        }

        _yongHuLiuChengViewModel.onDoingDocumentPageLiveData.observe(this) {
            if (it) {
                toNextActivity(
                    activity = RenZhengDocumentActivity::class.java,
                    mode = IntentFlagMode.SINGLE_TOP
                )
            }
        }

        _yongHuLiuChengViewModel.onDoingSelfiePageLiveData.observe(this) {
            if (it) {
                toNextActivity(
                    activity = RenZhengSelfieActivity::class.java,
                    mode = IntentFlagMode.SINGLE_TOP
                )
            }
        }

        _yongHuLiuChengViewModel.onAllDoneLiveData.observe(this) {
            if (it.isNotBlank()) {
                // to shen qing ye
                toNextActivity(
                    activity = RenZhengAllDoneActivity::class.java,
                    mode = IntentFlagMode.SINGLE_TOP,
                    params = hashMapOf<String, String>().apply {
                        put("titles", it)
                    }
                )
            }
        }

        _yongHuJiDingYiViewModel.onCheckYongHuDataLiveData.observe(this) {
            println(_yongHuJiDingYiViewModel.onCheckYongHuDataLiveData.value)
        }

        _yongHuJiDingYiViewModel.onSaveYongHuDataLiveData.observe(this) {
            if (it) {
                _yongHuLiuChengViewModel.requestYongHuLiuCheng()
            }
        }
    }

    private fun configUIState() {

    }

    @SuppressLint("NotifyDataSetChanged")
    private fun configUIEvent() {

        _fillSelectListDialogFragment = FillItemSelectListDialogFragment()

        _binding.atRenZhengNav.initConfig(
            text = getString(R.string.certification_text_1),
            textColor = "#000000",
            leftResId = R.drawable.dres_39,
            rightResId = R.drawable.dres_38
        ) {
            if (0 == it) {
                toNextActivity(
                    activity = HomeBeforeActivity::class.java,
                    mode = IntentFlagMode.SINGLE_TOP
                )
            } else if (1 == it) {
                val dialog = KeFuDialogFragment()
                dialog.showNow(supportFragmentManager, "kefu")
            }
        }

        _binding.atRenZhengDoingSubmit.setOnClickListener {
            val salaryUrls = _certifyViewModel.validSalaryUrls()
            val selfieUrls = _certifyViewModel.validSelfieUrls()

            val companyName = _binding.atCertifyCompanyName.calResult()
            val businessType = _binding.atCertifyBusinessType.calResult()
            val companyAddress = _binding.atCertifyCompanyAddress.calResult()
            val salary = _binding.atCertifySalary.calResult().replace(".", "")
            val pDate = _binding.atCertifySalaryDate.calResult()

            if (salaryUrls.isNotBlank() and
                selfieUrls.isNotBlank() and
                (companyName.isNotBlank()) and
                (businessType.isNotBlank()) and
                (companyAddress.isNotBlank()) and
                (salary.isNotBlank()) and
                (pDate.isNotBlank())
            ) {
                val maxLimitNum = SysConfigTool.filterMaxJinE().toInt()
                val stepJinE = SysConfigTool.filterStepJinE().toInt()
                var salaryNum = ((salary.toInt() / stepJinE) * stepJinE)
                salaryNum = min(salaryNum, maxLimitNum)
                val salaryNumFormat = salaryNum.toString()

                _yongHuJiDingYiViewModel.requestSaveYongHuJiDingYi(
                    companyName = companyName,
                    businessType = businessType,
                    companyAddress = companyAddress,
                    salary = salaryNumFormat,
                    pDate = pDate,
                    salaryUrls = salaryUrls,
                    selfieUrls = selfieUrls
                )
            }

            //
            addTouch(type = "certify_submit_click")
        }

        _binding.atCertifySalary.addNumberInputType()

        _certifyViewModel.initSalaryImageList()
        _certifySalaryImageAdapter =
            CertifySalaryImageAdapter(_certifyViewModel.salaryImageList) { action, position ->
                if (action == 0) {
                    // add
                    _certifyViewModel.imageType = 0
                    toDocumentActivity()

                    //
                    addTouch(type = "certify_gongzhi_proof_add_click")

                } else {
                    // delete
                    _certifyViewModel.salaryImageListRemove(position)
                    _certifySalaryImageAdapter.notifyDataSetChanged()
                }
            }

        _binding.atCertifySalaryProofList.layoutManager = GridLayoutManager(this, 3)
        _binding.atCertifySalaryProofList.adapter = _certifySalaryImageAdapter

        _certifyViewModel.initSelfieImageList()
        _certifySelfieImageAdapter =
            CertifySelfieImageAdapter(_certifyViewModel.selfieImageList) { action, position ->
                if (action == 0) {
                    // add
                    _certifyViewModel.imageType = 1
                    toDocumentActivity()
                } else {
                    // delete
                    _certifyViewModel.selfieImageListRemove(position)
                    _certifySelfieImageAdapter.notifyDataSetChanged()
                }
            }

        _binding.atCertifySelfieProofList.layoutManager = LinearLayoutManager(this)
        _binding.atCertifySelfieProofList.adapter = _certifySelfieImageAdapter

        _binding.atCertifySelfieProofAdd.setOnClickListener {
            // add
            _certifyViewModel.imageType = 1
            toDocumentActivity()

            //
            addTouch(type = "certify_selfie_proof_add_click")
        }

        // 跳转相册监听
        _pickMedia =
            registerForActivityResult(ActivityResultContracts.PickVisualMedia()) { uri ->
                if (uri != null) {
                    _certifyViewModel.handlePhotoAlbumResult(
                        this@CertifyActivity,
                        uri,
                        onConversionCompleted = { type, bitmap, position ->
                            updateImagePathResult(type, bitmap, position)
                        },
                        onUploadCompleted = { type, url, position ->
                            updateImageUrlResult(type, url, position)
                        })
                } else {
                    Log.d("PhotoPicker", "No media selected")
                }
            }
    }

    private fun configUIData() {

        _binding.atCertifyCompanyName.addTitle(getString(R.string.certification_text_8))
        _binding.atCertifyCompanyName.addHint(getString(R.string.certification_text_13))
        _binding.atCertifyCompanyName.addTag("companyName")

        val businessTypes = _yongHuJiDingYiViewModel.businessTypes()
        _binding.atCertifyBusinessType.addTitle(getString(R.string.certification_text_9))
        _binding.atCertifyBusinessType.addHint(getString(R.string.certification_text_14))
        _binding.atCertifyBusinessType.addTag("businessType")
        _binding.atCertifyBusinessType.addClickListener { fTag, _ ->
            _fillSelectListDialogFragment.apply {
                addTitle(this@CertifyActivity.getString(R.string.certification_text_9))
                addDataSource(businessTypes)
                addClickListener { _, jsonObject ->
                    val content = jsonObject.optString("value", "")
                    _binding.atCertifyBusinessType.addContent(content)
                }
                showNow(supportFragmentManager, fTag)
            }
        }

        _binding.atCertifyCompanyAddress.addTitle(getString(R.string.certification_text_10))
        _binding.atCertifyCompanyAddress.addHint(getString(R.string.certification_text_15))
        _binding.atCertifyCompanyAddress.addTag("companyAddress")

        _binding.atCertifySalary.addTitle(getString(R.string.certification_text_11))
        _binding.atCertifySalary.addHint(getString(R.string.certification_text_16))
        _binding.atCertifySalary.addTag("salary")

        val salaryDays = _yongHuJiDingYiViewModel.salaryDays()
        _binding.atCertifySalaryDate.addTitle(getString(R.string.certification_text_12))
        _binding.atCertifySalaryDate.addHint(getString(R.string.certification_text_17))
        _binding.atCertifySalaryDate.addTag("salaryDate")
        _binding.atCertifySalaryDate.addClickListener { fTag, _ ->
            _fillSelectListDialogFragment.apply {
                addTitle(this@CertifyActivity.getString(R.string.certification_text_12))
                addDataSource(salaryDays)
                addClickListener { _, jsonObject ->
                    val content = jsonObject.optString("value", "")
                    _binding.atCertifySalaryDate.addContent(content)
                }
                showNow(supportFragmentManager, fTag)
            }
        }

        _yongHuJiDingYiViewModel.requestYongHuJiDingYi()
    }

    private fun checkPermission(): Boolean {
        return EasyPermissions.hasPermissions(
            this,
            android.Manifest.permission.CAMERA
        )
    }

    private fun requestPermission() {
        EasyPermissions.requestPermissions(
            this,
            getString(R.string.disclosure_text_11),
            300,
            android.Manifest.permission.CAMERA
        )
    }

    private fun toDocumentActivity() {
        if (checkPermission()) {
            val dialog = DocumentSourceTypeDialogFragment {
                if (DocumentSourceTypeDialogFragment.TYPE_TAKE_PIC == it) {
                    val intent = Intent(
                        this@CertifyActivity,
                        RenZhengDocumentCaptureActivity::class.java
                    )
                    intent.putExtra("title", "")
                    startActivityForResult(
                        intent,
                        RenZhengDocumentCaptureActivity.REQUEST_CODE_DOCUMENT_CAPTURE
                    )

                } else if (DocumentSourceTypeDialogFragment.TYPE_PHOTO_ALBUM == it) {
                    _pickMedia.launch(PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly))
                }
            }
            dialog.showNow(supportFragmentManager, "document")

        } else {
            requestPermission()
        }
    }

    /**
     * 选择图片结果回调
     * @param type 0:身份证正面，1：行驶证正反面，2：护照正面
     * @param bitmap 图片Bitmap对象
     * @param position 位置，0：第一张，1：第二张
     */
    @SuppressLint("NotifyDataSetChanged")
    private fun updateImagePathResult(type: Int, bitmap: Bitmap?, position: Int) {
        if (_certifyViewModel.imageType == 0) {
            _certifySalaryImageAdapter.notifyDataSetChanged()
        } else {
            _certifySelfieImageAdapter.notifyDataSetChanged()
        }
    }

    /**
     * 上传图片结果回调
     * @param type 0:身份证正面，1：行驶证正反面，2：护照正面
     * @param url 图片url
     * @param position 位置，0：第一张，1：第二张
     */
    @SuppressLint("NotifyDataSetChanged")
    private fun updateImageUrlResult(type: Int, url: String?, position: Int) {
        if (_certifyViewModel.imageType == 0) {
            _certifySalaryImageAdapter.notifyDataSetChanged()
        } else {
            _certifySelfieImageAdapter.notifyDataSetChanged()
        }
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray,
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this)
    }

    override fun onRationaleAccepted(requestCode: Int) {
        requestPermission()
    }

    override fun onRationaleDenied(requestCode: Int) {
    }

    override fun onPermissionsDenied(requestCode: Int, perms: List<String>) {
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            SettingsDialog.Builder(this).build().show()
        }
    }

    override fun onPermissionsGranted(requestCode: Int, perms: List<String>) {

    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == DEFAULT_SETTINGS_REQ_CODE) {
            requestPermission()

        } else if (requestCode == RenZhengDocumentCaptureActivity.REQUEST_CODE_DOCUMENT_CAPTURE) {
            if (resultCode == RESULT_OK) {
                val imageOutputPath = data?.getStringExtra("path")
                // 更新页面
                _certifyViewModel.handleTakePictureResult(
                    result = imageOutputPath,
                    onConversionCompleted = { type, bitmap, position ->
                        updateImagePathResult(type, bitmap, position)
                    },
                    onUploadCompleted = { type, url, position ->
                        updateImageUrlResult(type, url, position)
                    })
            }
        }
    }


    override fun onResume() {
        super.onResume()

        addTouch(type = this.javaClass.simpleName, isOpen = true)
    }

    override fun onPause() {
        super.onPause()

        addTouch(type = this.javaClass.simpleName, isComplete = true)
    }
}

